package com.ljf.app1;

import com.ljf.framework.exception.LjfExceptionHandler;
import com.ljf.framework.result.JsonResult;
import com.ljf.framework.result.JsonResultEnum;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 说明：可以拦截servlet所有的异常，包括filter和controller层
 *
 * @Auther: lijinfeng
 * @Date: 2024/4/25
 */
@RestController
public class LjfErrorController extends BasicErrorController {


    public LjfErrorController() {
            super(new DefaultErrorAttributes(), new ErrorProperties());
    }


    /**
     * produces 设置返回的数据类型：application/json
     *
     * @param request 请求
     * @return 自定义的返回实体类
     */
    @Override
    @RequestMapping(value = "", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {

        JsonResultEnum jsonResultEnum = LjfExceptionHandler.getExceptionForServlet();
        HttpStatus httpStatus;
        if (jsonResultEnum.getCode() == 500) {
            // 服务端异常，状态码为500
            httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            // 其余异常（手动throw）为逻辑校验，状态码为200
            httpStatus = HttpStatus.OK;
        }
        return new ResponseEntity(JsonResult.error(jsonResultEnum), httpStatus);
    }

}
